package com.smrtcold.dev.task;

import com.alibaba.fastjson.JSONObject;
import com.smrtcold.dev.dto.dev.task.DevTask;
import com.smrtcold.dev.dto.dev.base.Point;
import com.smrtcold.dev.dto.dev.base.PointGroup;
import com.smrtcold.dev.dto.dev.base.XMZDevInfo;
import com.smrtcold.dev.init.SystemInit;
import com.smrtcold.dev.mapper.DataMapper;
import com.smrtcold.dev.service.base.BaseServer;
import lombok.extern.log4j.Log4j2;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;


/**
 * 这段为恒伟定制化程序
 * 1.先读取机组的吸气压力，频率--->如果吸气压力小于0.4pa 并且当前运行的机组的评率>=50Hz 执行后续操作
 * 2.判断制冷中的风机数量>=4 执行后续操作
 * 3.如果当前温度无明显下降趋势，接近停机温度， 且超过了10分钟（阈值）--->每次读取判断是不是太复杂，在读取数据过工程是否可以实时记录？
 * 4. 如果-1 后大于风机保护值 执行风机-1 操作
 * <p>
 * <p>
 * 优化后逻辑：
 * 1.先判断当前温度是否接近停机温度
 * 2.再次执行以上逻辑----
 */
@Log4j2
@Service
public class SetParamJob implements Job {


    private Long mid = 0L;

    private Long taskid;

    private int status = 0;
    @Value("${sys.apid}")
    private String apid;
    @Autowired
    private DataMapper dataMapper;

    @Autowired
    private BaseServer baseServer;


    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        StringBuffer logContert = new StringBuffer();
        DevTask task = (DevTask) context.getJobDetail().getJobDataMap().get("TASK");
        this.taskid = task.getId();
        this.mid = task.getMid();

        try {
            boolean isallSuccess = this.run(logContert, task);
            status = 1;
            if (logContert.length() > 5) {
                this.baseServer.push(String.format("/%s/task/log/%s/%s", apid, mid, taskid), logContert.toString());
            }
        } catch (Exception e) {
            status = 0;
            log.error("任务执行失败：{}", e.getMessage());
            logContert.append(e.getMessage());
            //            todo 推送异常日志
            // push(String.format("HMI/%s/%s/log", apid, taskid), logContert.toString());
        }
        if (logContert.length() > 5) {
            this.dataMapper.addlog(taskid, status, 0, logContert.toString());
        }
    }

    /**
     * 执行任务
     *
     * @param logContert
     * @param
     * @throws Exception
     */
    private boolean run(StringBuffer logContert, DevTask task) throws Exception {
        String parameters = task.getParameters();
        List<PointGroup> pointGroups = JSONObject.parseArray(parameters, PointGroup.class);
        int successCount = 0, errorCount = 0;
        for (PointGroup pointGroup : pointGroups) {
            if (this.setParameters(logContert, pointGroup)) {
                successCount++;
            } else {
                errorCount++;
            }
        }
        return successCount == pointGroups.size();





    }

    /**
     * @param logContert
     * @param pointGroup
     * @throws Exception
     */
    public boolean setParameters(StringBuffer logContert, PointGroup pointGroup) {
        XMZDevInfo xmzDevInfo = SystemInit.get(pointGroup.getDevid());
        try {
            //vD 80：当前温度    VD274:停止值  VD270 启动值
            List<Point> points = pointGroup.getPoints();
            if (null == points || points.size() == 0) return true;
            StringBuffer newlog = new StringBuffer();
            Map<String, Number> values = null;
            for (int i = 0; i < 3; i++) {
                try {
                    values = xmzDevInfo.getValues(points);
                    break;
                } catch (Exception e) {
                   log.error("获取点位值失败：{}", e.getMessage());
                }
            }
            for (Point point : points) {
                try {
                    Number number = values.get(point.getAddres());
                    if (null == number || !point.getValue().toString().equals(number.toString())) {
                        xmzDevInfo.writeByAddres(point.getAddres(), point.getValue());
                        newlog.append(String.format("点位：%s 值：%s -> %s \r\n", point.getName(), number, point.getValue()));
                    } else {
                        newlog.append(String.format("点位：%s 值：%s-->%s 无需设置 \r\n", point.getName(), number, point.getValue()));
                    }
                } catch (Exception e) {
                    newlog.append(String.format("设置点位：%s 值：%s -失败！ \r\n",  point.getName(), point.getValue()));

                }
            }
            if (newlog.length() > 0) {
                logContert.append(pointGroup.getName() + newlog + "\r\n");
            }
            return true;
        } catch (Exception e) {
            logContert.append(pointGroup.getName() + "执行失败：" + e.getMessage() + "\r\n");
            log.error("设置{}点位失败：{}", pointGroup.getName(), e.getMessage());
        }
        return false;
    }


}
